package jgl.vajra.management.part.mine.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jgl.vajra.management.R;
import jgl.vajra.management.bean.CarDocumentTypeBean;
import jgl.vajra.management.bean.HomeCarModelBean;
import jgl.vajra.management.bean.PeripheralPoiBean;
import jgl.vajra.management.databinding.ActivityCarInformationBinding;
import jgl.vajra.management.databinding.ItemCarInformationBinding;
import jgl.vajra.management.event.MapPointEvent;
import jgl.vajra.management.event.PaymentSuccessEvent;
import jgl.vajra.management.listener.MessageDlialogListener;
import jgl.vajra.management.listener.MyToolbarViewListener;
import jgl.vajra.management.manager.AccountManager;
import jgl.vajra.management.manager.FragmentManager;
import jgl.vajra.management.manager.IntentManager;
import jgl.vajra.management.part.mine.contract.CarInformationContract;
import jgl.vajra.management.part.mine.viewModel.CarInformationViewModel;
import jgl.vajra.management.part.vehicle.pop.DocumentTypePop;
import jgl.vajra.management.utils.RandomUtils;
import jgl.vajra.management.widget.bean.ProfileFileBean;
import jgl.vajra.management.widget.databindingadapter.BaseBindingItemPresenter;
import jgl.vajra.management.widget.databindingadapter.BaseDataBindingDecorator;
import jgl.vajra.management.widget.databindingadapter.SingleTypeBindingAdapter;
import jgl.vajra.management.widget.dialogfragment.MessageDialogFragment;
import jgl.vajra.management.widget.interfaces.ImagePickerListener;
import jgl.vajra.management.widget.interfaces.UploadListener;
import jgl.vajra.management.widget.manager.UploadFileMapManager;
import jgl.vajra.management.widget.mvvm.factory.CreateViewModel;
import jgl.vajra.management.widget.mvvm.view.BaseMVVMActivity;
import jgl.vajra.management.widget.retrofithelper.utils.AEACCoder;
import jgl.vajra.management.widget.utils.PickFileToolsV2;
import jgl.vajra.management.widget.utils.ToastUtils;
import jgl.vajra.management.widget.utils.UIUtils;

@CreateViewModel(CarInformationViewModel.class)
public class CarInformationActivity extends BaseMVVMActivity<CarInformationViewModel, ActivityCarInformationBinding> implements CarInformationContract.View, BaseBindingItemPresenter<CarDocumentTypeBean.CarDocumentBean> {

    private DocumentTypePop documentTypePop;
    private MessageDialogFragment messageDialogCarInformation;
    private PickFileToolsV2 pickFileTools;
    private HomeCarModelBean carTypeData;
    private SingleTypeBindingAdapter adapter;
    private String logo;
    private int hasCannonHead = 0;
    private PeripheralPoiBean addressBean;
    private List<CarDocumentTypeBean> carDocumentTypeBeans;
    private MessageDialogFragment messageDialogAdditional;
    private String fee;
    private int jobType;
    private String equipmentName;
    private String equipmentType;
    private boolean isAdd;
    private boolean isEdit;

    @Override
    public int getLayoutId() {
        return R.layout.activity_car_information;
    }

    @Override
    public void initView() {
        super.initView();
        mBinding.setView(this);

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

        carTypeData = getIntent().getParcelableExtra("itemData");

        jobType = getIntent().getIntExtra("jobType", 0);
        fee = getIntent().getStringExtra("fee");
        equipmentName = getIntent().getStringExtra("equipmentName");
        equipmentType = getIntent().getStringExtra("equipmentType");
        isAdd = getIntent().getBooleanExtra("isAdd", false);

        mBinding.etEquipmentName.setText(equipmentName);
        mBinding.etEquipmentType.setText(equipmentType);

        if (!TextUtils.isEmpty(equipmentName)) {
            setEtNoModification(mBinding.etEquipmentName);
            setEtNoModification(mBinding.etEquipmentType);
        }

        if (jobType == 1) {
            mBinding.tvType1.setBackgroundResource(R.drawable.shape_color_0f2cbb_4dp_edge);

        } else if (jobType == 2) {
            mBinding.tvType2.setBackgroundResource(R.drawable.shape_color_0f2cbb_4dp_edge);
        }


        if ("excavator".equals(carTypeData.type))
            mBinding.rlGunHead.setVisibility(View.VISIBLE);
        else
            mBinding.rlGunHead.setVisibility(View.GONE);


        mBinding.toolbar.setMyToolbarViewListener(new MyToolbarViewListener() {
            @Override
            public void onRightTextClick() {
                super.onRightTextClick();
                if (documentTypePop == null)
                    documentTypePop = new DocumentTypePop(CarInformationActivity.this);
                documentTypePop.showPopupWindow(mBinding.getRoot());
            }
        });


        // 不可嵌套滑动
        mBinding.recyclerView.setNestedScrollingEnabled(false);
        // 取消head 的 recycleView的焦点
        mBinding.recyclerView.setFocusableInTouchMode(false);
        //设置布局管理器
        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new SingleTypeBindingAdapter(this, null, R.layout.item_car_information);
        mBinding.recyclerView.setAdapter(adapter);
        adapter.setItemPresenter(this);
        adapter.setItemDecorator((BaseDataBindingDecorator<CarDocumentTypeBean, ItemCarInformationBinding>) (binding, position, viewType, data) -> {

            // 不可嵌套滑动
            binding.itemRecyclerView.setNestedScrollingEnabled(false);
            // 取消head 的 recycleView的焦点
            binding.itemRecyclerView.setFocusableInTouchMode(false);
            //设置布局管理器
            binding.itemRecyclerView.setLayoutManager(new GridLayoutManager(this, 2));
            SingleTypeBindingAdapter itemAdapter = new SingleTypeBindingAdapter(this, data.titleBean, R.layout.item_car_details_item);
            binding.itemRecyclerView.setAdapter(itemAdapter);
            itemAdapter.setItemPresenter(this);

        });

        requestNetData();
    }

    private void requestNetData() {
        //获取车辆唯一编号
        // mViewModel.getRandomOrderNumber();

        Map<String, Object> map = new HashMap<>();
        map.put("Authorization", AEACCoder.encrypt(RandomUtils.getRandom()));//随机数
        //  map.put("model", carTypeData.model);
        map.put("type", 1);//1 - 车主端，2 - 司机端
        mViewModel.getCarDocumentTypeData(map);
    }

    @Override
    public void onCarType(int type) {
        if (!isAdd) return;
        if (isEdit) return;
        if (type == 1) {
            mBinding.tvType1.setBackgroundResource(R.drawable.shape_color_0f2cbb_4dp_edge);
            mBinding.tvType2.setBackgroundResource(R.drawable.shape_color_eeeeee_4dp);
        } else if (type == 2) {
            mBinding.tvType2.setBackgroundResource(R.drawable.shape_color_0f2cbb_4dp_edge);
            mBinding.tvType1.setBackgroundResource(R.drawable.shape_color_eeeeee_4dp);
        }
        jobType = type;
    }

    //地址
    @Override
    public void onAddress() {
        IntentManager.toMapPointActivity(this);
    }

    //是否有炮头
    @Override
    public void onGunHead() {
        if (messageDialogAdditional == null) {
            messageDialogAdditional = FragmentManager.getMessageDialogAdditional(new MessageDlialogListener() {
                @Override
                public void onRightClick() {
                    hasCannonHead = 1;
                    mBinding.tvGunHead.setText("是");
                }

                @Override
                public void onLeftClick() {
                    hasCannonHead = 0;
                    mBinding.tvGunHead.setText("否");
                }
            });
        }
        messageDialogAdditional.show(getSupportFragmentManager());
    }

    //确定提交
    @Override
    public void onDetermine() {
        for (int i = 0; i < carDocumentTypeBeans.size(); i++) {
            if (carDocumentTypeBeans.get(i).isRequired) {
                for (int j = 0; j < carDocumentTypeBeans.get(i).titleBean.size(); j++) {
                    if (TextUtils.isEmpty(carDocumentTypeBeans.get(i).titleBean.get(j).fileId)) {
                        ToastUtils.showShort(carDocumentTypeBeans.get(i).topic);
                        return;
                    }
                }
            }
        }

        if (AccountManager.getInstance().getLoginData(UIUtils.getContext()).tag==1){
            IntentManager.toSubmitSuccessActivity(CarInformationActivity.this);
            finish();
        }else {
            IntentManager.toImmediatePaymentActivity(this, AEACCoder.decrypt(fee), logo);
        }


      /*  if (messageDialogCarInformation == null) {
            messageDialogCarInformation = FragmentManager.getMessageTitleDialogCarInformation(new MessageDlialogListener() {
                @Override
                public void onRightClick() {
                    IntentManager.toMachineGuyActivity(CarInformationActivity.this, logo);
                }

                @Override
                public void onLeftClick() {
                    IntentManager.toSubmitSuccessActivity(CarInformationActivity.this);
                }
            });
        }
        messageDialogCarInformation.show(getSupportFragmentManager());*/
    }

    @Override
    public void returnCarDocumentTypeData(List<CarDocumentTypeBean> data) {
        carDocumentTypeBeans = data;

        for (int i = 0; i < data.size(); i++) {
            data.get(i).titleBean = new ArrayList<>();
            for (int j = 0; j < data.get(i).title.size(); j++) {
                CarDocumentTypeBean.CarDocumentBean bean = new CarDocumentTypeBean.CarDocumentBean();
                bean.name = data.get(i).title.get(j);
                bean.tag = data.get(i).tag;
                bean.type = data.get(i).type;
                bean.url = "";
                data.get(i).titleBean.add(bean);
            }
        }

        adapter.refresh(data);
    }

    @Override
    public void returnRandomOrderNumberSuccess(String randomOrderNumber) {
        // logo =randomOrderNumber;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (pickFileTools != null) {
            pickFileTools.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    protected boolean isRegisterEvent() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMapPointEvent(MapPointEvent event) {
        addressBean = event.bean;

        mBinding.tvAddress.setText(addressBean.address + addressBean.detailedAddress);
        mBinding.tvAddress.setTextColor(UIUtils.getColor(R.color.color_333333));
    }

    @Override
    public void onItemClick(int position, CarDocumentTypeBean.CarDocumentBean itemData) {

        if (jobType == 0) {
            ToastUtils.showShort("请选择设备类型");
            return;
        }

        String equipmentName = mBinding.etEquipmentName.getText().toString().trim();
        if (TextUtils.isEmpty(equipmentName)) {
            ToastUtils.showShort("请输入设备名称");
            return;
        }
        String equipmentType = mBinding.etEquipmentType.getText().toString().trim();
        if (TextUtils.isEmpty(equipmentType)) {
            ToastUtils.showShort("请输入设备型号");
            return;
        }

        if (addressBean == null) {
            ToastUtils.showShort("请选择车辆常停的位置");
            return;
        }

        logo = mBinding.etFrame.getText().toString().trim();
        if (TextUtils.isEmpty(logo)) {
            ToastUtils.showShort("请输入车架号码");
            return;
        }

        String vehicleAge = mBinding.etVehicleAge.getText().toString().trim();
        if (TextUtils.isEmpty(vehicleAge)) {
            ToastUtils.showShort("请输入该车的车龄");
            return;
        }

        String otherInfo = mBinding.etOtherInfo.getText().toString().trim();

        if (pickFileTools == null)
            pickFileTools = PickFileToolsV2.init(this);
        pickFileTools.pick(true, 0, new ImagePickerListener() {
            @Override
            public void onPickImageList(List<String> imgs, int tag) {
                super.onPickImageList(imgs, tag);
                String avatarUrl = imgs.get(0);

                Map<String, Object> map = new HashMap<>();
                map.put("Authorization", AccountManager.getInstance().getLoginData(UIUtils.getContext()).authorization);

                if (isAdd) {
                    map.put("model", URLEncoder.encode(equipmentName));
                } else {
                    map.put("model", carTypeData.model);
                }

                map.put("logo", logo);
                map.put("tag", itemData.tag);
                map.put("type", itemData.type);
                map.put("longitude", addressBean.longitude);
                map.put("latitude", addressBean.latitude);
                map.put("city", URLEncoder.encode(addressBean.city));
                map.put("address", URLEncoder.encode(addressBean.address + addressBean.detailedAddress));

                map.put("jobType", jobType);
                map.put("name", URLEncoder.encode(equipmentName));
                map.put("age", vehicleAge);
                map.put("otherInfo", URLEncoder.encode(otherInfo));

                if ("excavator".equals(carTypeData.type))
                    map.put("hasCannonHead", hasCannonHead);

                if (!TextUtils.isEmpty(itemData.fileId))
                    map.put("fileId", itemData.fileId);


                UploadFileMapManager.getInstance().uploadPathMap(map, avatarUrl, "", new UploadListener() {
                    @Override
                    public void onUploadSuccess(List<ProfileFileBean> file) {

                    }

                    @Override
                    public void onUploadStringSuccess(List<String> file) {
                        itemData.url = avatarUrl;
                        itemData.fileId = file.get(0);
                        adapter.refresh();

                        isEdit = true;
                        setEtNoModification(mBinding.etEquipmentName);
                        setEtNoModification(mBinding.etEquipmentType);
                        setEtNoModification(mBinding.etFrame);
                        setEtNoModification(mBinding.etVehicleAge);
                    }

                    @Override
                    public void onUploadFailed() {

                    }
                });
            }
        });
    }

    //禁止修改
    public void setEtNoModification(EditText editText) {
        editText.setFocusable(false);
        editText.setLongClickable(false);
        editText.setTextIsSelectable(false);
    }

    //支付成功
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPaymentSuccessEvent(PaymentSuccessEvent event) {
        finish();
    }
}
